package fw.asmx.launcher;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import fw.asmx.launcher.adapter.AlphabeticalOrderClassifyAppListAdapter;
import fw.asmx.launcher.adapter.item.AppItem;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

import java.util.ArrayList;
import java.util.List;

public class AppListActivity extends Activity
{
    private StickyListHeadersListView stkLv;

    private ArrayList<AppItem>[] al_ai;
    private AlphabeticalOrderClassifyAppListAdapter ada_list;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applist);
        if (savedInstanceState == null)
        {
            stkLv = (StickyListHeadersListView) findViewById(R.id.lv_applist);
            //
            //

            //
            ArrayList<AppItem> al = getAppList();
            //
            ada_list = new AlphabeticalOrderClassifyAppListAdapter(this, R.layout.lv_appitem_head,
                                                                   R.layout.lv_appitem);
            for (AppItem ai : al)
            {
                ada_list.addItem(ai.getAppName(), ai);
            }


            //
            TextView t=new TextView(this);
            stkLv.setAdapter(ada_list);
            stkLv.setOverScrollMode(View.OVER_SCROLL_NEVER);
            stkLv.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    String pkg=((AppItem)ada_list.getItem(position)).getPkgName();
                    startActivity(getPackageManager().getLaunchIntentForPackage(pkg));
                }
            });
        }
    }

    private ArrayList<AppItem> getAppList()
    {
        PackageManager m = getPackageManager();
        ArrayList<AppItem> al = new ArrayList<>();
        Intent i = new Intent(Intent.ACTION_MAIN, null);
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> lst = m.queryIntentActivities(i, 0);
        for (ResolveInfo ri : lst)
        {
            AppItem ai =
                    new AppItem(ri.loadLabel(m).toString(), ri.activityInfo.packageName,
                                ri.activityInfo.loadIcon(m));
            al.add(ai);
        }
        return al;
    }
}
